import React, { useRef, useState } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api from '../../services/api';
import { Plugin } from '../../types';

const PluginList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const fetchPlugins = async (params: any) => {
    try {
      const response = await api.get('/plugins/', {
        params: {
          skip: (params.current - 1) * params.pageSize,
          limit: params.pageSize,
        },
      });
      const pluginsData = Array.isArray(response.data) ? response.data : response.data.items || [];
      const total = Array.isArray(response.data) ? response.data.length : response.data.total || 0;
      return {
        data: pluginsData,
        success: true,
        total: total,
      };
    } catch (error: any) {
      message.error('Failed to fetch plugins');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleDelete = async (id: number) => {
    setLoading(true);
    try {
      await api.delete(`/plugins/${id}`);
      message.success('Plugin deleted successfully');
      actionRef.current?.reload();
    } catch (error: any) {
      message.error(error.response?.data?.detail || 'Failed to delete plugin');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<Plugin>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      copyable: true,
    },
    {
      title: 'Description',
      dataIndex: 'description',
      ellipsis: true,
      search: false,
    },
    {
      title: 'Type',
      dataIndex: 'pluginType',
      render: (_, record) => {
        const typeColors: Record<string, string> = {
          'MCP': 'blue',
          'OpenAPI': 'green',
        };
        const pluginType = record.pluginType || 'MCP';
        return (
          <Tag color={typeColors[pluginType] || 'default'}>
            {pluginType}
          </Tag>
        );
      },
      valueEnum: {
        MCP: { text: 'MCP', status: 'Processing' },
        OpenAPI: { text: 'OpenAPI', status: 'Success' },
      },
    },
    {
      title: 'Endpoint',
      dataIndex: 'endpoint',
      ellipsis: true,
      copyable: true,
      search: false,
      render: (_, record) => record.endpoint || <span style={{ color: '#999' }}>Not Set</span>,
    },
    {
      title: 'Auth Method',
      dataIndex: 'authMethod',
      render: (_, record) => {
        const authColors: Record<string, string> = {
          'none': 'default',
          'bearer': 'blue',
          'api_key': 'green',
          'basic': 'orange',
        };
        const authMethod = record.authMethod || 'none';
        return (
          <Tag color={authColors[authMethod] || 'default'}>
            {authMethod.toUpperCase()}
          </Tag>
        );
      },
      valueEnum: {
        none: { text: 'None', status: 'Default' },
        bearer: { text: 'Bearer', status: 'Processing' },
        api_key: { text: 'API Key', status: 'Success' },
        basic: { text: 'Basic', status: 'Warning' },
      },
    },
    {
      title: 'Created At',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: 'Action',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          icon={<EditOutlined />}
          onClick={() => navigate(`/plugins/edit/${record.id}`)}
        >
          Edit
        </Button>,
        <Popconfirm
          key="delete"
          title="Are you sure to delete this plugin?"
          onConfirm={() => handleDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <Button type="link" danger icon={<DeleteOutlined />} loading={loading}>
            Delete
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<Plugin>
      columns={columns}
      actionRef={actionRef}
      request={fetchPlugins}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: true,
      }}
      dateFormatter="string"
      headerTitle="Plugin Management"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => navigate('/plugins/create')}
          type="primary"
        >
          Create Plugin
        </Button>,
      ]}
    />
  );
};

export default PluginList;
